<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="55">
        <template #default="{ $index }">
          {{ (queryParams.currentPage - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="生产编号" align="center" prop="produceId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品图片" width="100" align="center" prop="productImage">
        <template #default="scope">
          <img width="50" height="50" :src="scope.row.productImage" alt="">
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="count" />
      <el-table-column label="执行标准" align="center" prop="standardNum" />
      <el-table-column label="查看详情" width="120" align="center" v-if="type == 1 || type == 2">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span v-if="type == 1">
            <span v-if="scope.row.status == 1">待生产</span>
            <span v-else>已生产</span>
          </span>
          <span v-if="type == 2">
            <span v-if="scope.row.status == 2">待质检</span>
            <span v-else>已质检</span>
          </span>
          <span v-if="type == 3">
            <span v-if="scope.row.status == 3">待入库</span>
            <span v-else>已入库</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作人员" align="center" prop="updateUserName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="type == 3 && scope.row.status == 3" link type="primary" icon="View"
            @click="produceStorageFinishApi(scope.row.produceId)">入库</el-button>

          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.currentPage"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改生产对话框 -->
    <el-dialog ialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <!-- 1生产 2质检 3入库 -->
          <el-col :span="12" v-if="form.type == 1 || form.type == 2">
            <el-form-item label="流程" prop="produceProcessId">
              <el-select v-model="form.produceProcessId" placeholder="请选择生产流程">
                <el-option v-for="dict in processList" :key="dict.produceProcessId" :label="dict.name"
                  :value="dict.produceProcessId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择商品">
                <el-option v-for="dict in productList" :key="dict.productId" :label="dict.name"
                  :value="dict.productId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="数量" prop="count">
              <el-input v-model="form.count" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == 3">
            <el-form-item label="生产日期" prop="produceDate">
              <el-date-picker v-model="form.produceDate" value-format="YYYY-MM-DD" type="date" />
            </el-form-item>
          </el-col>



        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生产质检步骤详情 -->
    <el-dialog :title="title" v-model="openDetail" width="780px" append-to-body>

      <el-table :data="form.stepList" style="width: 100%">
        <el-table-column label="步骤" prop="content" />
        <el-table-column label="打卡姓名" prop="employeeName" />
        <el-table-column label="打卡时间" prop="time" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleFinish(scope.row)">打卡</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script setup name="Notice">

import { useRoute } from 'vue-router';
const route = useRoute();

const type = ref(route.meta.menuId);



// 在 script 部分添加状态处理函数
function getStatusType(status) {
  switch (status) {
    case 1: return 'warning'  // 待生产
    case 2: return 'info'     // 待质检
    case 3: return 'primary'  // 待入库
    case 4: return 'success'  // 已入库
    default: return 'info'
  }
}

function getStatusLabel(status) {
  switch (status) {
    case 1: return '待生产'
    case 2: return '待质检'
    case 3: return '待入库'
    case 4: return '已入库'
    default: return '未知'
  }
}


import {
  produceStorageFinish,
  listProduceStepFinish,
  listProduceStep,
  listProduce,
  getNotice,
  delProduce,
  addProduce,
  updateNotice,
} from "@/api/backProduce/backProduce";

import { listProcess } from "@/api/backProduce/backProduce";
import { listProduct } from "@/api/backProduct/backProduct";
import { ref, watch } from 'vue';
let processList = ref([]);
listProcess().then((response) => {
  console.log(response);
  processList.value = response.records;
});

let productList = ref([]);
listProduct().then((response) => {
  console.log(response);
  productList.value = response.records;
});

const { proxy } = getCurrentInstance();

const noticeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    currentPage: 1,
    pageSize: 10,
    noticeTitle: undefined,
    createBy: undefined,
    status: undefined,
  },
  rules: {
    noticeTitle: [
      { required: true, message: "生产标题不能为空", trigger: "blur" },
    ],
    noticeType: [
      { required: true, message: "生产类型不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);


watch(route, () => {
  type.value = route.meta.menuId;
  if (type.value == "1186") {
    type.value = "1";
  } else if (type.value == '1892117165070520322') {
    type.value = "2";
  } else if (type.value == '1892117423766802434') {
    type.value = "3";
  }
}, {
  immediate: true
})


/** 查询生产列表 */
function getList() {
  loading.value = true;
  // 设置生产类型
  queryParams.value.type = type.value;
  listProduce(queryParams.value).then((response) => {
    noticeList.value = response.records;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    stepList: [],
    produceId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    noticeContent: undefined,
    type: type.value
  };
  proxy.resetForm("noticeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.currentPage = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.produceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  /* 1 2 3 生产 质检 入库 */
  if (type.value == "1") {
    title.value = "添加生产";
  } else if (type.value == "2") {
    title.value = "添加质检";
  } else if (type.value == "3") {
    title.value = "添加入库";
  }
}

/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  const produceId = row.produceId || ids.value;
  getNotice(produceId).then((response) => {
    form.value = response;
    open.value = true;
    if (type.value == "1") {
      title.value = "修改生产";
    } else if (type.value == "2") {
      title.value = "修改质检";
    } else if (type.value == "3") {
      title.value = "修改入库";
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {

      if (form.value.produceId != undefined) {
        updateNotice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        console.log(form.value, 'form');
        addProduce(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const produceIds = row.produceId || ids.value;
  proxy.$modal
    .confirm('是否确认删除生产编号为"' + produceIds + '"的数据项？')
    .then(function () {
      return delProduce(produceIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}



const openDetail = ref(false);

function updateStepList(response) {
  form.value.stepList = response;
}

/**修改按钮操作 */
function handleDetail(row) {
  reset();
  const produceId = row.produceId || ids.value;

  listProduceStep({
    produceId: produceId,
    type: type.value
  }).then((response) => {
    updateStepList(response);
    form.value.produceId = produceId
    openDetail.value = true;
    title.value = "生产质检步骤详情";
  });

}

function handleFinish(row) {
  console.log(row, 'row');
  const produceStepId = row.produceStepId || ids.value;
  listProduceStepFinish({
    produceStepId: produceStepId,
    type: type.value
  }).then((response) => {
    // 刷新质检步骤列表

    listProduceStep({
      produceId: form.value.produceId,
      type: type.value
    }).then((response) => {
      updateStepList(response);
      getList();
    });
    proxy.$modal.msgSuccess("打卡成功");
  }).catch(() => {
    proxy.$modal.msgError("打卡失败");
  });
}


function produceStorageFinishApi(produceId) {
  produceStorageFinish(produceId).then((response) => {
    getList();
    proxy.$modal.msgSuccess("入库成功");
  }).catch(() => {
    proxy.$modal.msgError("入库失败");
  });
}


getList();

</script>